package com.heima.behavior.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.behavior.mapper.ApFollowBehaviorMapper;
import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.behavior.service.ApFollowBehaviorService;
import com.heima.model.behavior.dtos.FollowBehaviorDto;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.behavior.pojos.ApFollowBehavior;
import com.heima.model.common.constants.HotArticleConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.mess.app.UpdateArticleMess;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.UUID;

/**
 * @Description:
 * @Version: V1.0
 */
@Service
public class ApFollowBehaviorServiceImpl extends ServiceImpl<ApFollowBehaviorMapper, ApFollowBehavior>
        implements ApFollowBehaviorService {

    @Autowired
    ApBehaviorEntryService apBehaviorEntryService;

    @Autowired
    KafkaTemplate kafkaTemplate;
    /**
     * 存储关注数据
     * @param dto
     * @return
     */
    @Override
    public ResponseResult saveFollowBehavior(FollowBehaviorDto dto) {
        //没有提供远程服务接口  本地调用不需要判空
        ApBehaviorEntry apBehaviorEntry = apBehaviorEntryService.findByUserIdOrEquipmentId(dto.getUserId(), null);
        if (apBehaviorEntry == null) {
            //如果查询到的实体为空 (行为实体是在注册User用户的时候添加的)
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
//        先查后增
        ApFollowBehavior followBehavior = getOne(Wrappers.<ApFollowBehavior>lambdaQuery()
                .eq(ApFollowBehavior::getEntryId, apBehaviorEntry.getId())
                .eq(ApFollowBehavior::getFollowId, dto.getFollowId())
                .eq(ApFollowBehavior::getArticleId,dto.getArticleId())
                );

        //记录关注关系
        if (followBehavior == null) {
            followBehavior = new ApFollowBehavior();
            followBehavior.setEntryId(apBehaviorEntry.getId());
            followBehavior.setArticleId(dto.getArticleId());
            followBehavior.setCreatedTime(new Date());
            followBehavior.setFollowId(dto.getFollowId());//设置这个关注者的userID
            save(followBehavior);
        }

        UpdateArticleMess mess = new UpdateArticleMess();
        mess.setType(UpdateArticleMess.UpdateArticleType.COLLECTION);
        mess.setArticleId(dto.getArticleId());
        kafkaTemplate.send(HotArticleConstants.HOTARTICLE_SCORE_INPUT_TOPIC,
                JSON.toJSONString(mess));

        //取消关注的话删除用户关系表
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
